<template>
    <div>
        <div class="margin-bottom20">
            <el-button @click="activitySummarize" type="primary">生成概况分析（AI）</el-button>
            <el-button @click="showUserDialog" type="primary">生成学员分析（AI）</el-button>
        </div>
        <div>
            <ActivitySummarizeIndex :data="data" :activitySummarize="true" :activityUserSummarize="true">
            </ActivitySummarizeIndex>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="选择分析成员" width="800">
        <template #header>
            <span class="icon-text el-dialog__header-title">
                <el-icon class="text-primary">
                    <Guide />
                </el-icon>
                比赛成员分析
            </span>
        </template>
        <div class="dialog-content">
            <el-select v-model="selectedUserIds" multiple filterable clearable collapse-tags collapse-tags-tooltip
                placeholder="请选择要分析的比赛成员（不选则默认为全部成员）" style="width: 100%">
                <el-option v-for="user in users" :key="user?.ID"
                    :label="user?.xingming ? `${user.xingming} (${user?.name})` : user?.name"
                    :value="Number(user?.ID)" />
            </el-select>
            <div class="selected-count" v-if="selectedUserIds.length > 0">
                已选择 {{ selectedUserIds.length }} 位成员
            </div>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="activityUserSummarize">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { uniqBy } from 'lodash-es';
import { computed, ref } from 'vue';
import { useStore } from 'vuex';
import { asyncCreateActivitysummarize, asyncCreateActivityusersummarize } from '../../../api';
import ActivitySummarizeIndex from '../../../components/AI/activitySummarizeIndex.vue';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';

const p = defineProps<{ data: Studycodemodel.Iactivity }>()

const store = useStore(Storekey)
const dialogVisible = ref(false)
const selectedUserIds = ref<number[]>([])

// 计算用户列表
const users = computed(() => {
    const t1 = p.data.activityuser?.map(c => c.user) || [];
    const t2 = p.data.team?.user ? [p.data.team.user] : [];
    const t3 = p.data.team?.teamuser?.map(c => c.user) || [];
    return uniqBy([...t1, ...t2, ...t3].filter(Boolean), user => user?.ID);
});

// 显示成员选择对话框
function showUserDialog() {
    selectedUserIds.value = []
    dialogVisible.value = true
}

async function activitySummarize() {
    try {
        await asyncCreateActivitysummarize({ activityid: p.data.ID });
        ElMessage.success('比赛分析任务创建成功');
    } catch (error) {
        if (error instanceof Error) {
            ElMessage.error(error.message || '提交失败');
        }
    }
}

async function activityUserSummarize() {
    try {
        const params = {
            activityid: p.data.ID,
            // 如果选择了成员则传userid，否则不传（服务器默认处理全部）
            ...(selectedUserIds.value.length > 0 && { userid: selectedUserIds.value })
        }
        await asyncCreateActivityusersummarize(params);
        ElMessage.success(selectedUserIds.value.length > 0 ? `已开始分析选中的 ${selectedUserIds.value.length} 位成员` : '已开始分析全部成员');
        dialogVisible.value = false;
    } catch (error) {
        if (error instanceof Error) {
            ElMessage.error(error.message || '提交失败');
        }
    }
}

</script>

<style scoped>
.margin-bottom20 {
    margin-bottom: 20px;
}

.dialog-content {
    padding: 0 20px;
}

.selected-count {
    margin-top: 10px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
}

.icon-text {
    display: flex;
    align-items: center;
    gap: 8px;
}

.text-primary {
    color: var(--el-color-primary);
}
</style>